package com.example.jdbconectiontest.config;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.springframework.stereotype.Component;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

@Component
public class MyMysqlPool {

    String mysqlIp;
    Integer mysqlPort;
    String mysqlPwd;
    String mysqlUser;
    String mysqlDB;
    public static List<Connection> cs = new LinkedList<>();

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public MyMysqlPool(String mysqlIp, Integer mysqlPort, String mysqlPwd, String mysqlUser, String mysqlDB, int size) throws SQLException {
        this.mysqlIp = mysqlIp;
        this.mysqlPort = mysqlPort;
        this.mysqlPwd = mysqlPwd;
        this.mysqlUser = mysqlUser;
        this.mysqlDB = mysqlDB;

        for (int i = 0; i < size; i++) {
            Connection connection = DriverManager.getConnection("jdbc:mysql://" + mysqlIp + "/" + mysqlDB + "?characterEncoding=UTF-8", mysqlUser, mysqlPwd);
            cs.add(connection);
        }
    }

    public MyMysqlPool() {

    }

    public synchronized Connection getConnection() {
        while (cs.isEmpty()) {
            try {
                System.out.println(1);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Connection c = cs.remove(0);
        return c;
    }

    public synchronized void closeConnection(Connection c) {
        //使用完了记得把连接放回连接池
        cs.add(c);
        //唤醒wait告诉它有新的连接池可用
        this.notifyAll();
    }

    public MysqlDataSource mysqlDataSource() {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setServerName(mysqlIp);
        mysqlDataSource.setPort(mysqlPort);
        mysqlDataSource.setPassword(mysqlPwd);
        mysqlDataSource.setUser(mysqlUser);
        mysqlDataSource.setDatabaseName(mysqlDB);
        return mysqlDataSource;
    }
}
